<?php

namespace App\Models;

use App\Admin\Traits\AdminBuilder;
use App\Admin\Traits\CanValidate;
use DB;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use Notifiable;
    use AdminBuilder;
    use CanValidate;
    use HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username', 'nickname', 'password', 'avatar', 'union_id',
    ];

    public function validateRules()
    {
        $rules = [
            'username' => 'bail|required|max:20|unique:users,username,'.(int) $this->id,
            'nickname' => 'bail|nullable|max:20',
            'avatar'   => 'max:255',
        ];

        $rules = $this->handlePasswordRules($rules);

        return $rules;
    }

    private function handlePasswordRules($rules)
    {
        if (!$this->exists || $this->password != \Request::get('password') || !\Request::get('password')) {
            $rules += [
                'password' => 'required|between:6,20|confirmed',
            ];
        }

        return $rules;
    }

    public function validateMessages()
    {
        return [];
    }

    public function validateAttributes()
    {
        return [
            'username' => '用户名',
            'nickname' => '昵称',
            'avatar'   => '头像',
        ];
    }

    public static function convertWechatData($data)
    {
        $newData = [
            'union_id' => $data['unionid'],
            'avatar'   => $data['headimgurl'],
            'nickname' => $data['nickname'],
        ];
        array_forget($data, ['unionid', 'headimgurl', 'nickname']);
        $newData = array_merge($newData, $data);

        return $newData;
    }
}
